package nirvana.core.bean.json.file.filePath;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import nirvana.core.bean.json.file.storage.impl.AliOssFileStorage;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;

/**
 * 【描 述】：
 * 【环 境】：J2SE 11
 * 【详 细】：
 *
 * @author 李松林
 * @version v1.0 2023-02-01 新建
 * @since 2023-02-01
 */
@Component
@ConditionalOnProperty(value = "fileStorageModel",havingValue = "oss")
public class OssFilePathSerializer extends JsonSerializer<String> {

    private final AliOssFileStorage fileStorage;

    public OssFilePathSerializer(AliOssFileStorage fileStorage) {
        this.fileStorage = fileStorage;
    }


    /**
     * 序列化时相对路径获取向oss请求完整路径
     *
     * @param path
     * @param jsonGenerator
     * @param serializerProvider
     * @throws IOException
     */
    @Override
    public void serialize(String path, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {

        String packagePath = "";
        if (StringUtils.hasText(path)) {
            //包装路径
            packagePath = fileStorage.packagePath(path);
        }
        jsonGenerator.writeString(packagePath);
    }
}
